//
//  TcpServerUtil.m
//  TestTcpUdp
//
//  Created by leeson zhong on 2021/7/6.
//

#import "TcpServerUtil.h"
#import "GCDAsyncSocket.h"

@interface TcpServerUtil()<GCDAsyncSocketDelegate>{
    int serverPort;
    NSString *clientIp;
    int clientPort;
}

// 服务端socket(开放端口,监听客户端socket的连接)
@property (strong, nonatomic) GCDAsyncSocket *serverSocket;
//连接上服务端的客户端
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;

@end

@implementation TcpServerUtil

-(BOOL)initWithServerPort:(int)port{
    // 初始化服务端socket
    self.serverSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    BOOL result = [self.serverSocket acceptOnPort:port error:&error];
    if (result == NO && self.delegate) {
        self.serverSocket = nil;
        [self.delegate onTcpServerClose];
    }else{
        serverPort = port;
    }
    return result;
}

-(BOOL)sendData:(NSData *)data{
    if (self.clientSocket) {
        [self.clientSocket writeData:data withTimeout:-1 tag:0];
        return YES;
    }else{
        return NO;
    }
}

-(void)close{
    if (self.serverSocket) {
        [self.serverSocket disconnect];
    }
}

-(int)getServerPort{
    return serverPort;
}
-(NSString *)getClientIp{
    return clientIp;
}
-(int)getClientPort{
    return clientPort;
}


#pragma mark GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    self.clientSocket = newSocket;
    clientIp = newSocket.connectedHost;
    clientPort = newSocket.connectedPort;
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    [self.delegate onTcpServerAcceptClient:YES ClientIp:clientIp ClientPort:clientPort];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    if (self.delegate) {
        [self.delegate onTcpServerReceiveData:data ClientIp:sock.connectedHost ClientPort:sock.connectedPort];
    }
    //一直请求读取否则会接收不到数据
    [sock readDataWithTimeout:-1 tag:tag];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err{
    if (self.delegate) {
        if (sock == self.serverSocket) {
            [self.delegate onTcpServerAcceptClient:NO ClientIp:nil ClientPort:0];
            self.serverSocket = nil;
            [self.delegate onTcpServerClose];
        }else {
            [self.delegate onTcpServerAcceptClient:NO ClientIp:sock.connectedHost ClientPort:sock.connectedPort];
        }
    }
}

@end
